// packageD/pages/authorize.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    height: app.globalData.height,
    titleBarHeight: app.globalData.titleBarHeight,
    windowHeight: app.globalData.windowHeight,
    navHeight: app.globalData.navHeight - 2,
    // 组件所需的参数
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '快捷登录', //导航栏 中间的标题
      color: '#FFFFFF'
    },
    authorize: 0,
    code: '',
    session_key: "",
    cods: 1,
    wx_num: 1,
    type: 1,
    slog: false,
    isCheck:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  back: function () {
    let pages = getCurrentPages();
    console.log(pages)
    if (pages[0].route === "packageD/pages/authorize/authorize") {
      wx.switchTab({
        url: '../../../pages/index/index',
      })
    }
    else {
      if (pages[pages.length - 2].route !== "packageD/pages/authorize/authorize") {
        wx.navigateBack()
      }else{
        wx.redirectTo({
          url: '/'+pages[pages.length - 3].route
        })
      }
      
    }
  },
  phoneLogin() {
    wx.navigateTo({
      url: '../login/login',
    });

  },
  toAgreement() {
    wx.navigateTo({
      url: '../agreement/agreement',
    });

  },
  toConceal() {
    wx.navigateTo({
      url: '../conceal/conceal',
    });

  },
  toCheck: function () {
    this.setData({
      isCheck: !this.data.isCheck
    })

  },
  //返回到首页
  backHome: function () {
    wx.switchTab({
      url: '../../../pages/index/index',
    })
  },
  tost(){
    wx.showToast({
      title: '请先阅读用户协议和隐私政策',
      icon: 'none',
    });
  },
  toWeChat(e) {
    console.log(e)
    let that = this;
    if (!that.data.isCheck) {
      wx.showToast({
        title: '请先阅读用户协议和隐私政策',
        icon: 'none',
      });
      return
    }else{
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        wx.showToast({
          title: '授权被拒绝！登录才能获得更好的体验哦',
          duration: 1500,
          icon: "none"
        })
        // wx.redirectTo({
        //   url: '/packageD/pages/login/login'
        // })
        return;
      }
      let params = {
        encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            code: that.data.cods,
            sessionKey: that.data.session_key,
      }
      // console.log(params)
      // return
      // 检查登录态是否过期
      wx.checkSession({
        success(res) {
          // session_key 未过期，并且在本生命周期一直有效
          app.fly.post('/ma/login', {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            code: that.data.cods,
            session_key: that.data.session_key,
          })
            .then(function (res_) {
              if (res_.code ===  0) {
                wx.setStorageSync("token", res_.data.token)
                wx.navigateBack({
                  delta: 1
                })

              } else if (res_.code == 201) {
                that.data.wx_num++;
                that.setData({
                  type: 0,
                })
                if (that.data.wx_num < 3) {
                  that.toWeChat(e);
                } else {
                  wx.showToast({
                    title: "授权失败，请返回重新进入此页面",
                    icon: 'none',
                    duration: 2000
                  })
                }

              } else {
                wx.showToast({
                  title: res_.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
        },
        fail(err) {
          wx.showToast({
            title: "授权失败，请返回重新进入此页面",
            icon: 'none',
            duration: 2000
          })
        }
      })
    }

  },

  authorizeAgin() {
    let that = this;
    wx.login({
      success: res => {
        app.fly.post('/v1/common/wechatLogin', {
          encryptData: that.data.encryptData,
          iv: that.data.iv,
          code: res.code,
          type: 0,
          spread_code: wx.getStorageSync("spread_code") || ''
        })
          .then(function (res_) {
            if (res_.code == 200) {
              wx.setStorageSync('isLoad', 1)
              wx.setStorageSync('addCart', 1)
              wx.setStorageSync("token", res_.data.token)
              wx.setStorageSync('mobile', res_.data.user.mobile)
              // app.hideRed();
              let pages = getCurrentPages();
              if (pages[0].route === 'shop/pages/storeRun/storeRun') {
                if (res_.data.user.store_id) {
                  wx.reLaunch({
                    url: '/shop/pages/storeRun/storeRun?store_id=' + res_.data.user.store_id
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/my/my',
                  })
                }
              } else {
                if (pages[0].route === 'packageC/pages/order/order') {
                  wx.reLaunch({
                    url: '/packageC/pages/order/order?index=' + 3
                  })
                } else if (pages[0].route === 'pages/shopping/shopping') {
                  wx.reLaunch({
                    url: '/pages/shopping/shopping',
                  })
                } else {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            } else if (res_.code == 201) {
              that.data.wx_num++;
              if (that.data.wx_num < 30) {
                that.authorizeAgin();
              } else {
                wx.showToast({
                  title: "请点击手机号一键登录",
                  icon: 'none',
                  duration: 2000
                })
              }

            } else {
              wx.showToast({
                title: res_.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
      }
    })
  },
  // wx.login({
  //   success: res => {
  //     if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
  //       // 拒绝登录
  //       wx.showToast({
  //         title: '授权被拒绝',
  //         duration: 1500,
  //         icon: "none"
  //       })
  //     } else {
  //       wx.setStorageSync('sessionKey', e.detail.encryptedData)
  //       app.fly.post('/mall/v1/common/wechatLogin', {
  //         encryptData: e.detail.encryptedData,
  //         iv: e.detail.iv,
  //         code: res.code,
  //         spread_code: wx.getStorageSync("spread_code") || ''
  //       })
  //         .then(function (res_) {
  //           wx.setStorageSync('addCart', 1)
  //           wx.setStorageSync("token", res_.data.token)
  //           wx.setStorageSync('mobile', res_.data.user.mobile)
  //           wx.navigateBack({
  //             delta: 1
  //           })
  //         })
  //     }
  //   }
  // })
  //},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.login({
      success: function (res) {
        that.setData({
          cods: res.code
        })
      
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  filterViewMove() {
    return false;
  },
  toggleDlog() {
    this.setData({
      slog: false,
    });
    let pages = getCurrentPages();
    if (pages[0].route === 'shop/pages/storeRun/storeRun') {
      wx.switchTab({
        url: '/pages/my/my',
      })
    } else {
      if (pages[0].route === 'packageC/pages/order/order') {
        wx.reLaunch({
          url: '/packageC/pages/order/order?index=' + 3
        })
      } else if (pages[0].route === 'pages/shopping/shopping') {
        wx.reLaunch({
          url: '/pages/shopping/shopping',
        })
      } else {
        wx.navigateBack({
          delta: 1
        })
      }
    }
  },
  //获取用户信息
  btn_sub: function (e) {
    var that = this
    wx.getUserProfile({
      desc: '是',
      success: res => {
        app.fly.post('/v1/user/wechatAuth', {
          code: app.globalData.code,
          add_info:JSON.stringify(res.userInfo)
        })
          .then(function (resTwo_) {
            that.setData({
              slog: false
            })
            if (wx.getStorageSync("spread_code")) {
              let code = wx.getStorageSync("spread_code") || '';
              let time = wx.getStorageSync("time") || 0;
              app.bindSpread(code, time);
            }
            let pages = getCurrentPages();
            if (pages[0].route === 'shop/pages/storeRun/storeRun') {
              wx.switchTab({
                url: '/pages/my/my',
              })
            } else {
              if (pages[0].route === 'packageC/pages/order/order') {
                wx.reLaunch({
                  url: '/packageC/pages/order/order?index=' + 3
                })
              } else if (pages[0].route === 'pages/shopping/shopping') {
                wx.reLaunch({
                  url: '/pages/shopping/shopping',
                })
              } else {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
      }, fail(e) {
        that.setData({
          slog: false
        })
        if (wx.getStorageSync("spread_code")) {
          let code = wx.getStorageSync("spread_code") || '';
          let time = wx.getStorageSync("time") || 0;
          app.bindSpread(code, time);
        }
        let pages = getCurrentPages();
        if (pages[0].route === 'shop/pages/storeRun/storeRun') {
          wx.switchTab({
            url: '/pages/my/my',
          })
        } else {
          if (pages[0].route === 'packageC/pages/order/order') {
            wx.reLaunch({
              url: '/packageC/pages/order/order?index=' + 3
            })
          } else if (pages[0].route === 'pages/shopping/shopping') {
            wx.reLaunch({
              url: '/pages/shopping/shopping',
            })
          } else {
            wx.navigateBack({
              delta: 1
            })
          }
        }
        
      }
    })
    return
    wx.login({
      success: res_login => {
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: resOne_ => {

                  app.fly.post('/v1/yffWechatAuth', {
                    encryptData: resOne_.encryptedData,
                    iv: resOne_.iv,
                    code: res_login.code
                  })
                    .then(function (resTwo_) {
                      that.setData({
                        slog: false
                      })
                      if (wx.getStorageSync("spread_code")) {
                        let code = wx.getStorageSync("spread_code") || '';
                        let time = wx.getStorageSync("time") || 0;
                        app.bindSpread(code, time);
                      }
                      let pages = getCurrentPages();
                      if (pages[0].route === 'shop/pages/storeRun/storeRun') {
                        wx.switchTab({
                          url: '/pages/my/my',
                        })
                      } else {
                        if (pages[0].route === 'packageC/pages/order/order') {
                          wx.reLaunch({
                            url: '/packageC/pages/order/order?index=' + 3
                          })
                        } else if (pages[0].route === 'pages/shopping/shopping') {
                          wx.reLaunch({
                            url: '/pages/shopping/shopping',
                          })
                        } else {
                          wx.navigateBack({
                            delta: 1
                          })
                        }
                      }
                    })
                }
              })
            }
            else {
              that.setData({
                slog: false
              })
            }
          }
        })


      }
    })

  },
})